package librss;
import java.io.*;
import java.util.List;
import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;
/*
 * XMLHandler.java
 *
 * Created on March 7, 2009, 12:43 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author alvaro
 */
public class XMLHandler {
    
    private String file;
    private Document doc;
    
    /**
     * Creates a new instance of XMLHandler
     */
    public XMLHandler(String file) throws Exception {
        this.file = file;
        doc = readXML(file);
    }
    
    public Document getDocument(){
        return this.doc;
    }
    
    private Document readXML(String filePath) throws JDOMException, IOException {
        
        File f = new File(filePath);
        SAXBuilder b = new SAXBuilder(false);
        
        return b.build(f);
    }
    
    public List selectNodes(Document doc, String xPath) throws Exception {
        List list = null;
        XPath xPathProc = null;
        xPathProc = XPath.newInstance(xPath);
        list = xPathProc.selectNodes(doc);
        return list;
    }
    
    public String getTagText(String tag) throws Exception{
        return this.getTagText(tag, 0);
    }
    
    public Element getTagElement(String tag) throws Exception {
        return this.getTagElement(tag, 0);
    }
    
    public Element getTagElement(String tag, int index) throws Exception {
        List l = selectNodes(doc, tag);
        Element el = (Element) l.get(index);
        return el;
    }
    
    public String getTagText(String tag, int index) throws Exception {
        List l = selectNodes(doc, tag);
        Element el = (Element) l.get(index);
        return el.getText();
    }
    
    public void dumpFile() throws Exception {
        OutputStream os = null;
        os = new FileOutputStream(new File(file));
        
        XMLOutputter xml = new XMLOutputter();
        
        Format form = Format.getPrettyFormat();
        form.setExpandEmptyElements(true);
        form.setEncoding("ISO-8859-1");
        form.setIndent("\t");
        form.setLineSeparator("\n");
        xml.setFormat(form);
        
        xml.output(doc, os);
        os.close();
    }
    
}
